const drawingArea = document.getElementById('drawingArea');
let startX, startY;
let isDrawing = false;
let currentRect = null;

// 鼠标按下事件
drawingArea.addEventListener('mousedown', (e) => {
    isDrawing = true;
    startX = e.clientX - drawingArea.getBoundingClientRect().left;
    startY = e.clientY - drawingArea.getBoundingClientRect().top;

    // 创建新矩形
    currentRect = document.createElement('div');
    currentRect.className = 'rectangle';
    drawingArea.appendChild(currentRect);
});

// 鼠标移动事件
drawingArea.addEventListener('mousemove', (e) => {
    if (!isDrawing || !currentRect) return;

    const currentX = e.clientX - drawingArea.getBoundingClientRect().left;
    const currentY = e.clientY - drawingArea.getBoundingClientRect().top;

    // 计算矩形位置和尺寸
    const width = Math.abs(currentX - startX);
    const height = Math.abs(currentY - startY);
    const left = Math.min(startX, currentX);
    const top = Math.min(startY, currentY);

    // 更新矩形样式
    currentRect.style.width = `${width}px`;
    currentRect.style.height = `${height}px`;
    currentRect.style.left = `${left}px`;
    currentRect.style.top = `${top}px`;
});

// 鼠标释放事件
drawingArea.addEventListener('mouseup', () => {
    isDrawing = false;
    currentRect = null;
});

// 鼠标离开区域事件
drawingArea.addEventListener('mouseleave', () => {
    if (isDrawing) {
        // 如果鼠标离开时正在绘制，移除未完成的矩形
        if (currentRect && currentRect.parentNode) {
            currentRect.parentNode.removeChild(currentRect);
        }
        isDrawing = false;
        currentRect = null;
    }
});